package com.suntront.module_metertask.sort

import androidx.lifecycle.rxLifeScope
import com.mtjsoft.www.kotlinmvputils.base.BaseRecycleViewModel
import com.mtjsoft.www.kotlinmvputils.imp.AndCallBackListImp
import com.mtjsoft.www.kotlinmvputils.model.LoadState
import com.mtjsoft.www.kotlinmvputils.rxhttp.error.code
import com.mtjsoft.www.kotlinmvputils.rxhttp.error.msg
import com.suntront.lib_db.AppDatabase
import com.suntront.lib_db.table.UserT
import kotlinx.coroutines.async
import okhttp3.internal.wait

/**
 * @author mtj  ��������
 * @Package com.suntront.module_metertask.sort
 * @date 2020-05-27 16:24:47
 */

class UserTSortViewModel : BaseRecycleViewModel<UserT>() {

//    val adminId = MMKV.defaultMMKV().getString("AdminID", "")

    var rosterId = 0

    /**
     * 分页获取列表数据
     */
    override fun getListDataInThread(pager: Int, callBackListImp: AndCallBackListImp<UserT>) {
        rxLifeScope.launch({
            // 异步读取本地数据库
            val list: MutableList<UserT> = async {
                AppDatabase.getDb().userDao().queryUpLoadByRosterId(rosterId)
            }.await()
            callBackListImp.onSuccess(list)
        }, {
            //异常回调，这里的it为Throwable类型
            val code = it.code
            val msg = it.msg
            showToastUI(msg)
            loadState.postValue(LoadState.FAILED)
        })
    }

    fun save() {
        for (i in list.value!!.indices) {
            list.value!![i].rosterOrder = i + 1
        }
        rxLifeScope.launch({
            val i = async {
                AppDatabase.getDb().userDao().updateUsers(list.value!!)
                AppDatabase.getDb().meterDao().updateMetes(rosterId, true)
            }.await()
            showToastUI(if (i > 0) "保存成功" else "保存失败")
        }, {
            //异常回调，这里的it为Throwable类型
            val code = it.code
            val msg = it.msg
            showToastUI(msg)
        })
    }
}